package com.portal.sso.whitelist.server;

import cn.hutool.json.JSONUtil;
import com.portal.sso.core.model.WhitelistModel;
import com.portal.sso.whitelist.config.WhitelistConfig;
import com.portal.sso.whitelist.model.RespointModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

@Slf4j
@Data
@AllArgsConstructor
public class WhitelistModelServer {
    private JdbcTemplate jdbcTemplate;
    private StringRedisTemplate redisTemplate;

    /**
     * 读取持久化数据，然后保存到redis
     */
    public void Init() {
        try {
            String sql = "select * from portal_sso_whitelist";

            List<WhitelistModel> list = new ArrayList<WhitelistModel>();
            jdbcTemplate.queryForStream(sql, (row, rowIndex) -> {
                Map<String, String> map = new HashMap<String, String>();
                map.put("app_id", row.getString("app_id"));
                map.put("app_name", row.getString("app_name"));
                map.put("app_secret", row.getString("app_secret"));
                map.put("res_model", row.getString("res_model"));
                map.put("uri_style", row.getString("uri_style"));
                map.put("whitelist", row.getString("whitelist"));
                return map;
            }).forEach(map -> {
                //将数据存储到redis中
                redisTemplate.opsForHash().putAll(WhitelistConfig.WHITELIST_APP_PREFIX + map.get("app_id"), map);
            });
            log.info("白名单初始化完成");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

    public void AddItem(WhitelistModel model) {
        try {
            //验证数据
            if (!isExist(model.getAppId())) {
                String sql = "insert into portal_sso_whitelist values(?,?,?,?,?,?,?)";
                //添加到数据库
                jdbcTemplate.update(sql, UUID.randomUUID().toString(), model.getAppId(), model.getAppName(), model.getAppSecret(), model.getWhitelist(), model.getUriStyle(), model.getResModel());
                //更新redis
                upRedis(model);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void EditItem(WhitelistModel model) {
        if (isExist(model.getAppId())) {
            String sql = "update portal_sso_whitelist set app_name=?,app_secret=?,res_model=?,uri_style=?,whitelist=? where app_id=?";
            jdbcTemplate.update(sql, model.getAppName(), model.getAppSecret(), model.getResModel(), model.getUriStyle(), model.getWhitelist(), model.getAppId());
            //更新redis
            upRedis(model);
        }
    }

    public void DelItem(String appId) {
        try {

            if (isExist(appId)) {
                String sql = "delete from portal_sso_whitelist where app_id =?";
                jdbcTemplate.update(sql, appId);
                if(redisTemplate.hasKey(WhitelistConfig.WHITELIST_APP_PREFIX + appId)){

                    redisTemplate.delete(WhitelistConfig.WHITELIST_APP_PREFIX + appId);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 更新redis
     *
     * @param model
     */
    public void upRedis(WhitelistModel model) {
        try {
            //更新redis
            Map<String, String> map = new HashMap();
            map.put("app_id", model.getAppId());
            map.put("app_name", model.getAppName());
            map.put("app_secret", model.getAppSecret());
            map.put("res_model", model.getResModel());
            map.put("uri_style", model.getUriStyle());
            map.put("whitelist", model.getWhitelist());
            redisTemplate.opsForHash().putAll(WhitelistConfig.WHITELIST_APP_PREFIX + model.getAppId(), map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 判断app_id是否存在
     *
     * @param app_id
     * @return
     */
    public boolean isExist(String app_id) {
        try {
            String sql = "select count(1) from portal_sso_whitelist where app_id=?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, app_id);
            return count > 0;
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        return false;
    }

    /**
     * 所有客户端信息数据
     *
     * @return
     */
    public List<WhitelistModel> getListAll() {
        try {
            String sql = "select id, app_id, app_name, whitelist, uri_style, res_model  from portal_sso_whitelist";
            List<WhitelistModel> list = new ArrayList<WhitelistModel>();
                 jdbcTemplate.query(sql,(resultSet) -> {
                    WhitelistModel item = new WhitelistModel();
                    item.setId(resultSet.getString("id"));
                    item.setAppId(resultSet.getString("app_id"));
                    item.setAppName(resultSet.getString("app_name"));
                    item.setWhitelist(resultSet.getString("whitelist"));
                    item.setUriStyle(resultSet.getString("uri_style"));
                    item.setResModel(resultSet.getString("res_model"));
                     list.add(item);
                });

            return list;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

  /**
   * 获取json字符串
   * @return{
   *   "code": 0,
   *   "msg": "",
   *   "count": 1000,
   *   "data": [{}, {}]
   * }
   */
    public String getListAllJson() {


        List<WhitelistModel> list = getListAll();


        if (list != null) {
            RespointModel<List<WhitelistModel>> model = new RespointModel();
            model.setCode("0");
            model.setMsg("访问成功");
            model.setCount(list.size());
            model.setData(list);
            return JSONUtil.parse(model).toJSONString(0);

        }
        return null;
    }

    /**
     * 根据appid获取对应的密钥
     * @param appId
     * @return
     */
    public String getKey(String appId){
        try {
            String sql = "select app_secret from portal_sso_whitelist where app_id=?";
           String  appSecret = jdbcTemplate.queryForObject(sql,String.class,appId);
           return appSecret;
        }catch (Exception e){

        }
        return "";
    }
}
